package com.sprucetec.common.config;

import com.sprucetec.commons.registry.RegistryProxy;
import com.sprucetec.live.constants.RedisKeyConstant;
import com.sprucetec.live.constants.ZkCacheConstant;
import com.sprucetec.live.watcher.ZookeeperWatcher;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.PostConstruct;

/**
 * @ClassName ZookeeperConfig
 * @Description:
 * @Author Kenny
 * @Date 2020/4/26
 **/

@Configuration
@Slf4j
public class ZookeeperConfig {

    @Value("${dubbo.registry-address}")
    private String serverZookeeperAddress;

    private ZooKeeper zooKeeper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Bean("zookeeper")
    public ZooKeeper initZookeeper() throws Exception {
        // 创建观察者
        ZookeeperWatcher watcher = new ZookeeperWatcher();
        // 创建 Zookeeper 客户端
        ZooKeeper zooKeeper = new ZooKeeper(serverZookeeperAddress.split("//")[1], 100000, watcher);
        this.zooKeeper = zooKeeper;
        // 将客户端注册给观察者
        ZookeeperWatcher.zooKeeper = zooKeeper;
        // 注入redisTemplate
        ZookeeperWatcher.redisTemplate = redisTemplate;
        // 将配置好的 zookeeper 返回

        initSystemRootNode(zooKeeper);
        return zooKeeper;
    }


    private void initSystemRootNode(ZooKeeper zooKeeper) {
        try {
            // 先清空一下
            destorySystemRootNode();
            // 创建 zookeeper 商品售罄信息根节点
            String path = ZkCacheConstant.SYSTEM_PREFIX;
            if (zooKeeper != null && zooKeeper.exists(path, false) == null) {
                zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (KeeperException | InterruptedException e) {
            log.error("创建live节点", e);
        }
    }

    private void destorySystemRootNode() {
        try {
            // 创建 zookeeper 商品售罄信息根节点
            String path = ZkCacheConstant.SYSTEM_PREFIX;
            if (zooKeeper != null && zooKeeper.exists(path, false) == null) {
                zooKeeper.delete(path, -1);
            }
            trunctRedisData(); // 清空相关redis缓存
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void trunctRedisData() {
        redisTemplate.delete(RedisKeyConstant.LiveVideoResources.INTRANET_IP);
    }

}
